package com.my.controller;


import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonArray;
import com.my.pojo.Goods;
import com.my.pojo.ShopCart;
import com.my.service.IShopCartService;
import com.my.util.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/shopCart")
@CrossOrigin("*")
public class ShopCartController {
    IShopCartService shopCartService;

    @Autowired
    public void setShopCartService(IShopCartService shopCartService) {
        this.shopCartService = shopCartService;
    }

    RedisTemplate<String, String> redisTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private void putMessage(Map<String, String> map, String code, String message) {
        map.put("code", code);
        map.put("message", message);
    }

    private String listShopCartToJSON(List<ShopCart> shopCart) {
        JsonArray jsonArray = new JsonArray();
        for (ShopCart src : shopCart) {
            if (src.getStatus() != 0) {
                continue;
            }
            Goods goods = src.getGoods();
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("id", src.getCartId());
            jsonObject.addProperty("num", src.getNum());
            jsonObject.addProperty("goodsId", goods.getGoodsId());
            jsonObject.addProperty("goodsName", goods.getName());
            jsonObject.addProperty("goodsPrice", goods.getPrice());
            jsonObject.addProperty("goodsStatus", goods.getStatus());
            jsonObject.addProperty("goodsImg", goods.getImgUrl());
            jsonArray.add(jsonObject);
        }

        return jsonArray.toString();
    }

    @RequestMapping("/show")
    public String showGoods(Integer currentPage, Integer pageSize, String sort, Boolean asc, HttpServletRequest req) {
        String token = req.getHeader("token");
        Integer userId = JWTUtils.getId(token);
        System.out.println(userId);
        Map<String, String> map = new HashMap<>();
        if(userId == null) {
            this.putMessage(map, "500", "token解析失败");
        }
        Pageable pageable;
        if(pageSize != -1) {
            if (!"".equals(sort)) {
                Sort.Order order = new Sort.Order((asc ? Sort.Direction.ASC : Sort.Direction.DESC), sort);
                Sort s = new Sort(order);
                pageable = new PageRequest(currentPage, pageSize, s);
            } else {
                pageable = new PageRequest(currentPage, pageSize);
            }

            Page<ShopCart> shopCartPage = this.shopCartService.showShopCart(pageable, userId);
            if (shopCartPage.getContent().size() == 0) {
                this.putMessage(map, "200", "success");
                map.put("totalNum", shopCartPage.getTotalElements() + "");
                map.put("totalPages", shopCartPage.getTotalPages() + "");
                map.put("shopCart", listShopCartToJSON(shopCartPage.getContent()));
            }
        } else {
            List<ShopCart> listShopCart = shopCartService.showShopCart(userId);
            this.putMessage(map, "200", "success");
            map.put("shopCart", listShopCartToJSON(listShopCart));
        }
        return new Gson().toJson(map);
    }

    @RequestMapping("/add")
    public String addToShopCart(Integer goodsId, Integer num, HttpServletRequest req) {
        Map<String, String> map = new HashMap();
        if (goodsId <= 0 || num <= 0) {
            putMessage(map, "500", "错误参数");
        } else {
            Integer userId = JWTUtils.getId(req.getHeader("token"));
            System.out.println(userId);
            if (userId == null) {
                putMessage(map, "501", "token解析失败");
            } else {
                Integer res = shopCartService.addToShopCart(userId, goodsId, num);
                if (res > 0) {
                    putMessage(map, "200", "成功");
                } else if (res == -1) {
                    putMessage(map, "502", "用户不存在");
                } else if (res == -2) {
                    putMessage(map, "503", "商品不存在");
                } else if (res == -3) {
                    putMessage(map, "504", "库存不足");
                } else if (res == -4) {
                    putMessage(map, "505", "sql错误");
                } else {
                    putMessage(map, "555", "未知错误");
                }
            }
        }
        return new Gson().toJson(map);
    }

    @RequestMapping("/update")
    public String updateShopCart(Integer cartId, Integer num, HttpServletRequest req) {
        Map<String, String> map = new HashMap<String, String>();

        if (cartId <= 0 || num <= 0) {
            putMessage(map, "500", "错误参数");
        } else {
            Integer userId = JWTUtils.getId(req.getHeader("token"));
            if (userId == null) {
                putMessage(map, "501", "token解析失败");
            } else {
                Integer res = shopCartService.updateShopCart(cartId, num, userId);
                if (res == 0) {
                    putMessage(map, "200", "成功");
                } else if (res == -1) {
                    putMessage(map, "502", "购物车不存在");
                } else if (res == -2) {
                    putMessage(map, "503", "非法操作");
                } else if (res == -3) {
                    putMessage(map, "504", "商品不存在");
                } else if (res == -4) {
                    putMessage(map, "505", "库存不足");
                } else if (res == -5) {
                    putMessage(map, "506", "sql错误");
                } else {
                    putMessage(map, "555", "未知错误");
                }
            }
        }
        return new Gson().toJson(map);

    }

    @RequestMapping("/delete")
    public String deleteFromShopCart(Integer cartId, HttpServletRequest req) {
        Map<String, String> map = new HashMap<String, String>();

        if (cartId <= 0) {
            putMessage(map, "500", "错误参数");
        } else {
            Integer userId = JWTUtils.getId(req.getHeader("token"));
            if (userId == null) {
                putMessage(map, "501", "token解析失败");
            } else {
                Integer res = shopCartService.deleteFromShopCart(cartId, userId);
                if (res == -1) {
                    putMessage(map, "502", "购物车不存在");
                } else if (res == -2) {
                    putMessage(map, "503", "非法操作");
                } else if (res == -3) {
                    putMessage(map, "504", "sql错误");
                } else if (res == 0) {
                    putMessage(map, "200", "Success");
                } else {
                    putMessage(map, "555", "未知错误");
                }
            }
        }
        return new Gson().toJson(map);
    }

}
